package com.face.baidu_face;

import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.baidu.idl.face.api.manager.FaceConst;
import com.baidu.idl.face.api.manager.FaceInitCallback;
import com.baidu.idl.face.api.manager.FaceServiceCallbck;
import com.baidu.idl.face.api.manager.FaceServiceManager;
import com.baidu.idl.face.platform.FaceEnvironment;
import com.baidu.idl.facelive.api.FaceLiveManager;
import com.baidu.idl.facelive.api.entity.FaceLiveConfig;
import com.baidu.idl.facelive.api.entity.FaceLivenessType;
import com.baidu.idl.facelive.api.entity.LivenessValueModel;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.exception.OCRError;
//import com.baidu.ocr.sdk.model.AccessToken;
import com.face.baidu_face.api.APIService;
import com.face.baidu_face.api.ConsoleConfigManager;
import com.face.baidu_face.model.AccessToken;
import com.face.baidu_face.model.Config;
import com.face.baidu_face.model.ConsoleConfig;
import com.face.baidu_face.model.VerifyToken;
import com.face.baidu_face.model.LivenessVsIdcardResult;
import com.face.baidu_face.utils.PoliceCheckResultParser;
import com.face.baidu_face.exception.FaceException;

import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/**
 * BaiduFacePlugin
 */
public class BaiduFacePlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
    private MethodChannel channel;
    private Activity activity;
    private ConsoleConfig consoleConfig;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "baidu_face");
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        if (call.method.equals("init")) {
            String ak = call.argument("ak");
            String sk = call.argument("sk");
            String licenseKey = call.argument("licenseKey");
            getAccessToken(ak, sk, result);
            init(licenseKey);
        } else if (call.method.equals("liveDetect")) {
            //活体认证
            getVerifyToken("2", result);
        }
    }


    private void getAccessToken(String ak, String sk, Result result) {
        APIService.getInstance().init();
        APIService.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken r) {
                if (r != null && r.getAccessToken() != null) {
                    Log.e("baidu_face", "获取AccessToken成功");
                    result.success(true);
                }
            }

            @Override
            public void onError(com.face.baidu_face.exception.FaceException error) {
                if (error == null) {
                    return;
                }
                Log.e("baidu_face", error.getErrorCode() + ":" + error.getErrorMessage());
                result.success(false);
            }
        }, ak, sk);
    }

    private void init(String licenseKey) {
        // OCR初始化（初始化OCR SDK 使用的license是aip.license，名字不能修改）
        OCR.getInstance(activity).initAccessToken(new com.baidu.ocr.sdk.OnResultListener<com.baidu.ocr.sdk.model.AccessToken>() {
            @Override
            public void onResult(final com.baidu.ocr.sdk.model.AccessToken result) {
                if (!TextUtils.isEmpty(result.getAccessToken())) {
                    Log.d("ocr callback", "ocr init success!");
                }
            }

            @Override
            public void onError(final OCRError error) {
                Log.d("ocr callback", "resultCode:" + error.getErrorCode() + ",resultMsg:" + error.getMessage());

            }
        }, activity);

        consoleConfig = ConsoleConfigManager.getInstance(activity).getConfig();
        // 初始化
        FaceServiceManager.getInstance().init(activity, licenseKey, Config.LICENSE_NAME, Config.KEY_NAME, new FaceInitCallback() {
            @Override
            public void onCallback(int resultCode, String resultMsg) {
                Log.d("init callback", "resultCode:" + resultCode + ",resultMsg:" + resultMsg);
            }
        });
    }


    /**
     * 验证token
     *
     * @param matchSource
     */
    private void getVerifyToken(final String matchSource, Result result) {
        APIService.getInstance().initVerifyToken(activity, new OnResultListener<VerifyToken>() {
            @Override
            public void onResult(VerifyToken r) {
                if (r != null && r.getVerifyToken() != null) {
                    // 活体
                    startFaceLiveness(result);
                }
            }

            @Override
            public void onError(com.face.baidu_face.exception.FaceException error) {
                if (error == null) {
                    return;
                }
                Toast.makeText(activity, "网络异常，请检查网络连接", Toast.LENGTH_SHORT).show();
            }
        }, matchSource);
    }

    private void startFaceLiveness(Result result) {
        // 人脸阈值设置
        setFaceQualityConfig();
        // FaceServiceManager入参
        Map<String, Object> params = new HashMap<String, Object>();
//        // 必须携带verify_token
//        params.put("verify_token", APIService.getInstance().getVerifyToken());
//        // 开放平台控制台配置的方案Id
//        params.put("plan_id", consoleConfig.getPlanId());
//        params.put("match_source", 2);
        params.put("access_token", APIService.getInstance().getAccessToken());

        FaceServiceManager.getInstance().startFaceLiveness(activity, params, new FaceServiceCallbck() {
            @Override
            public void onCallback(final int resultCode, final Map<String, Object> resultMap) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

//                        String data = (String) resultMap.get(FaceConst.RESULT_JSON);
//                        PoliceCheckResultParser parser = new PoliceCheckResultParser();
//                        LivenessVsIdcardResult idcardResult = null;
//                        try {
//                            idcardResult = parser.parse(data);
//                            if (idcardResult == null) {
//                                Log.e("baidu_face", "LivenessVsIdcardResult->解析失败");
//                                return;
//                            }
//                        } catch (com.face.baidu_face.exception.FaceException e) {
//                            // 服务端错误
//                            Log.e("baidu_face", "LivenessVsIdcardResult->服务端错误");
//                        }

                        Map<String, Object> map = new HashMap<>();
//                        map.putAll(resultMap);
//                        map.remove("data");
                        map.put("resultCode", resultCode);
                        map.put("resultImage", resultMap.get("data"));
                        map.put("deviceId", resultMap.get("xDeviceId"));
                        map.put("sKey", resultMap.get("sKey"));
                        map.put("accessToken", APIService.getInstance().getAccessToken());

//                        Log.e("baidu_face", "------------------------------------> \n");
//                        JSONObject jsonObject = new JSONObject(map);
//                        Log.e("baidu_face", jsonObject.toString());
//                        Log.e("baidu_face", "------------------------------------> \n");

                        result.success(map);
                    }
                });
            }

            @Override
            public void onCancel() {
                result.success(null);
            }
        });
    }

    private void setFaceQualityConfig() {
        consoleConfig = ConsoleConfigManager.getInstance(activity).getConfig();
        try {
            FaceLiveConfig faceLiveConfig = new FaceLiveConfig();
            // faceUI默认展示结果页，此处必须设置为false
            faceLiveConfig.setShowResultView(false);
            // 设置模糊度阈值
            faceLiveConfig.setBlurnessValue(consoleConfig.getBlur());
            // 设置最小光照阈值（范围0-255）
            faceLiveConfig.setBrightnessValue(consoleConfig.getIllumination());
            // 设置最大光照阈值（范围0-255）
            faceLiveConfig.setBrightnessMaxValue(consoleConfig.getMaxIllumination());
            // 设置左眼遮挡阈值
            faceLiveConfig.setOcclusionLeftEyeValue(consoleConfig.getLeftEyeOcclu());
            // 设置右眼遮挡阈值
            faceLiveConfig.setOcclusionRightEyeValue(consoleConfig.getRightEyeOcclu());
            // 设置鼻子遮挡阈值
            faceLiveConfig.setOcclusionNoseValue(consoleConfig.getNoseOcclu());
            // 设置嘴巴遮挡阈值
            faceLiveConfig.setOcclusionMouthValue(consoleConfig.getMouthOcclu());
            // 设置左脸颊遮挡阈值
            faceLiveConfig.setOcclusionLeftContourValue(consoleConfig.getLeftCheekOcclu());
            // 设置右脸颊遮挡阈值
            faceLiveConfig.setOcclusionRightContourValue(consoleConfig.getRightCheekOcclu());
            // 设置下巴遮挡阈值
            faceLiveConfig.setOcclusionChinValue(consoleConfig.getChinOcclu());
            // 设置人脸姿态Pitch阈值
            faceLiveConfig.setHeadPitchValue(consoleConfig.getPitch());
            // 设置人脸姿态Yaw阈值
            faceLiveConfig.setHeadYawValue(consoleConfig.getYaw());
            // 设置人脸姿态Roll阈值
            faceLiveConfig.setHeadRollValue(consoleConfig.getRoll());
            // 录制视频
//            faceLiveConfig.setOpenRecord((Boolean) SharedPreferencesUtil.getData(this, SettingActivity.RECORD_ENABLE, false));
            faceLiveConfig.setOpenRecord(false);
            // 设置是否显示超时弹框
//            faceLiveConfig.setIsShowTimeoutDialog((Boolean) SharedPreferencesUtil.getData(this, SettingActivity.TIMEOUT_ENABLE, true));
            faceLiveConfig.setIsShowTimeoutDialog(true);
            // 输出图片类型：0原图、1抠图
            faceLiveConfig.setOutputImageType(FaceEnvironment.VALUE_OUTPUT_IMAGE_TYPE);
            // 是否忽略录制异常（只能忽略采集时间过短，采集后无文件输出的异常）
            faceLiveConfig.setIgnoreRecordError(true);
            // 眨眼张嘴遮挡开关
            faceLiveConfig.setActiveStrict(true);
            // 设置活体类型相关
            setFaceLivenessConfig(faceLiveConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setFaceLivenessConfig(FaceLiveConfig faceLiveConfig) {
        try {
            // 设置活体类型：炫彩活体、动作活体、静默活体
            FaceLivenessType faceLivenessType = null;
            // 配置活体动作集合、动作个数，活体阈值，无活体
            LivenessValueModel livenessValueModel = null;
            if (consoleConfig.getFaceLiveType() == 0) {
                faceLivenessType = FaceLivenessType.COLORLIVENESS;
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(true);
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(true);
                livenessValueModel = faceLiveConfig.getLivenessValueModel();
                livenessValueModel.actionList.addAll(consoleConfig.getActions());
                livenessValueModel.actionRandomNumber = consoleConfig.getFaceActionNum();
                livenessValueModel.livenessScore = consoleConfig.getLiveScore();
            } else if (consoleConfig.getFaceLiveType() == 1) {
                faceLivenessType = FaceLivenessType.ACTIONLIVENESS;
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(false);
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(true);
                livenessValueModel = faceLiveConfig.getLivenessValueModel();
                livenessValueModel.actionList.addAll(consoleConfig.getActions());
                livenessValueModel.actionRandomNumber = consoleConfig.getFaceActionNum();
                livenessValueModel.livenessScore = consoleConfig.getLiveScore();
            } else if (consoleConfig.getFaceLiveType() == 2) {
                faceLivenessType = FaceLivenessType.SILENTLIVENESS;
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(false);
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(false);
                livenessValueModel = faceLiveConfig.getLivenessValueModel();
                livenessValueModel.livenessScore = consoleConfig.getLiveScore();
            } else if (consoleConfig.getFaceLiveType() == 3) {
                // 是否开启炫彩活体能力
                faceLiveConfig.setIsOpenColorLive(true);
                // 是否开启动作活体能力
                faceLiveConfig.setIsOpenActionLive(false);
                livenessValueModel = faceLiveConfig.getLivenessValueModel();
            }
            // faceLiveConfig.setFaceLivenessType(faceLivenessType, livenessValueModel);
            faceLiveConfig.setLivenessValueModel(livenessValueModel);
            FaceLiveManager.getInstance().setFaceConfig(faceLiveConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        activity = binding.getActivity();
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {
        activity = null;
    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
        activity = binding.getActivity();
    }

    @Override
    public void onDetachedFromActivity() {
        activity = null;
    }
}
